package com.servlet.tellerservlet;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class TellerServlet
 */
@WebServlet("/TellerServlet")
public class TellerServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private int visitsCounter = 0;
	private final String SAVEPATH = "/WEB-INF/visitors.properties";

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public TellerServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	@Override
	public void init(ServletConfig config) throws ServletException {
		// TODO Auto-generated method stub
		super.init(config);
		this.visitsCounter = getSavedAmountOfVisitors();
		System.out.println("Started server. Found " + this.visitsCounter + " previous visitors.");
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		addVisitor();
		PrintWriter out = response.getWriter();
		out.println("You are visitor #" + this.visitsCounter);
		//http://www.jsptut.com/
	}
	
	private synchronized void addVisitor(){
		this.visitsCounter ++;
		if(this.visitsCounter % 25 == 0){
			//Save to file
			try{
				saveAmountOfVisitors(this.visitsCounter);
				System.out.println("Saved!");
			}catch (Exception e){
				System.err.println("Error: " + e.getMessage());
			}
		}
	}

	private void saveAmountOfVisitors(int amount){
		String filePath = getServletContext().getRealPath(SAVEPATH);
		try{
			File file = new File(filePath);
			FileOutputStream out = new FileOutputStream(file);
			out.write(String.valueOf(this.visitsCounter).getBytes());
			out.close();
		}catch(Exception e){System.out.println("Could not write visitor data.");}

	}

	private int getSavedAmountOfVisitors(){
		int visitors = 0;
		ServletContext context = getServletContext();

		InputStream inp = context.getResourceAsStream(SAVEPATH);
		if (inp != null) {
			try {
				InputStreamReader isr = new InputStreamReader(inp);
				BufferedReader reader = new BufferedReader(isr);
				String line = reader.readLine();
				reader.close();
				visitors = Integer.parseInt(line);
			} catch (IOException e) {System.out.println("Could not read previous visitor data.");}
		}
		return visitors;
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
